<%@ taglib prefix="stripes" uri="http://stripes.sourceforge.net/stripes.tld" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix='fn' uri='http://java.sun.com/jsp/jstl/functions' %>
<stripes:layout-render name="/layout/default.jsp" pageTitle="Your CSDCalendar" prototip="true" loggedIn="true" protoplasm="true">
    <stripes:layout-component name="html_head">
        <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/style/calendar.css"/>
        <style type="text/css">
            #calendar {
                width: 900px;
                margin: 0 auto;
            }
        </style>
        <script type="text/javascript">
            Protoplasm.use('datepicker');
            Protoplasm.use('upload');
        </script>
    </stripes:layout-component>
    <stripes:layout-component name="contents">
        <script type="text/javascript">
            var cal_id = parseInt('${cal.id}');
            var adding_event = false;
            var deleting_event = false;
            var events = $H();
            var startTime = new Date();
            var dayOffset = null;
            var activeDay;
            var otherDays;
            
            var jsonObj = ${jsonObj};
            var eventTemplate = new Template("<div id='cal-event-id-\#{id}' class='cal-event cal-event-skin cal-event-hori cal-event-draggable ui-corner-right \#{repeated}' onclick='deleteCalendarEvent(null, \#{id}); deleting_event = false'><span class='cal-event-time'>\#{time}</span><span class='cal-event-title'>\#{title}</span></div>");
            var tooltipTemplate = new Template("<div class='cal-tip ui-widget'><form action='${pageContext.request.contextPath}/account/InviteFriend.action'><input type='hidden' name='event.id' value='\#{id}' /><table class='event-table ui-widget ui-widget-content' style='width:100%; border-width:0px'><tr><td>Starts: </td><td><span>\#{starttime}</span></td></tr><tr><td>Ends: </td><td><span>\#{endtime}</span></td></tr><tr><td colspan='2'><span>\#{descr}</td></tr><tr><td>Invited:</td><td>\#{autocomplete}</td></tr>\#{invitees}<tr><td>Attachments: </td><td /></tr>\#{files}</table></form><form action='action/bucket/\#{account}/\#{id}/' enctype='multipart/form-data' method='post'><table class='event-table ui-widget ui-widget-content' style='width:100%; border-width:0px'><tr><td>Attach: </td><td><input type='file' name='file' class='attachment' /></td></tr></table></form></div>");
            
            function processJSON(JSONObj){
				new Effect.Pulsate($('monthlyBody'), { pulses: 1, duration: .5});

                startTime.setFullYear(JSONObj.startTime[0], JSONObj.startTime[1], JSONObj.startTime[2]);
                startTime.setSeconds(0);
                
                $('hidden_month').value = JSONObj.month;
                $('hidden_year').value = JSONObj.year;
                $('headerTitle').update(JSONObj.header);
                activeDay = JSONObj.activeDay;
                otherDays = JSONObj.otherDays;
                jsonObj = JSONObj;
				if (JSONObj.editable) {
					$('deleteEvnt').show();
					$('createNew').show();
				}
				else {
					$('deleteEvnt').hide();
					$('createNew').hide();
				}
				
				events = $H();
                
                for (day = 0; day < 42; day++) {
                    $('cal-day' + day).update(JSONObj.days[day].date);
                    
                    if (JSONObj.days[day].today) 
                        $$('td.cal-day' + day).invoke('addClassName', 'ui-state-highlight cal-today');
                    else if (JSONObj.days[day].otherMonth) 
                        $$('td.cal-day' + day).invoke('addClassName', 'cal-other-month');
                    
                    JSONObj.days[day].events.each(function(event){
						var e_id = event['repeated'] ? event['id'] + "_" + event['properStartTime'] : event['id'];
						var existing = events.get(e_id);
                        
						if (existing) 
							existing['endDay'] = day;
						else {
							event['startDay'] = day;
							event['endDay'] = day;
							events.set(e_id, event);
						}
						
                        $('cal-day' + day + '-content').insert(eventTemplate.evaluate({
                            id: e_id,
                            time: event.startTime,
                            title: event.title,
                            repeated: (event.repeated ? 'cal-event-repeated' : '')
                        }));
                        
                        invitees = ""
                        event.invites.each(function(inv){
                            invitees += inviteTemplate.evaluate({
                                name: inv.fullname,
                                action: '${pageContext.request.contextPath}/action/account/revoke/' + event.id + '/' + inv.id,
                                ajax: true
                            });
                        });
                        
                        
                        files = "";
                        event.files.each(function(file){
                            files += rowTemplate.evaluate({
                                name: fileTemplate.evaluate({
                                    href: file.href,
                                    filename: file.filename
                                })
                            });
                        });
                        
                        auto = autoTemplate.evaluate();
                        Element.extend(auto);
                        
                        var newTip = new Element('div');
                        newTip.insert(tooltipTemplate.evaluate({
                            id: e_id,
                            starttime: event.properStartTime,
                            endtime: event.properEndTime,
                            descr: event.description,
                            invitees: invitees,
                            files: files,	
                            autocomplete: auto,
                            account: JSONObj.account
                        }));
                        
                        new Tip('cal-event-id-' + e_id, newTip, {
                            title: event.title + (event.repeated ? '- repeated event' : ''),
                            closeButton: true,
                            style: 'default',
							delay: 1,
                            hideOn: {
                                element: 'closeButton',
                                event: 'click'
                            }
                        });
                        
                        $('cal-event-id-' + e_id).eventId = e_id;
                        
                        $('cal-event-id-' + e_id).observe('prototip:shown', function(e){
                            $$('input.autocomplete').each(function(elem){
                                autocomplete = new Ajax.Autocompleter(elem, Element.next(elem, '.results'), "${pageContext.request.contextPath}/action/auto/", {
                                    minChars: 3,
                                    frequency: .5,
                                    eventId: Event.element(e).eventId,
                                    afterUpdateElement: function(text, elem){
                                        elem.up('form').request();
                                        elem.up('tr').insert({
                                            after: inviteTemplate.evaluate({
                                                name: text.value,
                                                ajax: true,
                                                action: "${pageContext.request.contextPath}/action/revoke/" + this.eventId + "/" + text['suggestionid']
                                            })
                                        });
                                    }
                                });
                            });
                            $$('input.attachment').each(function(elem){
                                new Control.FileUpload(elem, {
                                    inline: true,
                                    progress: false,
                                    multiple: true
                                });
                            });
                        });
                    });
                }
                document.fire('csd:json');
            }
            
            function positionEvent(event, col, slot){
                event.clonePosition($('cal-col' + col), {
                    setHeight: false,
                    setTop: false
                });
                event.clonePosition(slot, {
                    setWidth: false,
                    setLeft: false
                });
            }
            
            function invoke(dummy, name){
                var params = {};
                if (name) 
                    params[name] = name;
                else 
                    params['today'] = 'today';
                
                $('hidden_form').request({
                    method: 'get',
                    evalJSON: true,
                    parameters: params,
                    onSuccess: function(transport){
                        $$('td.cal-today').each(function(elem){
                            elem.removeClassName('cal-today');
                            elem.removeClassName('ui-state-highlight');
                        });
                        $$('td.cal-other-month').invoke('removeClassName', 'cal-other-month');
                        $$('div.cal-event').invoke('remove');
                        
                        var JSONObj = transport.responseJSON;
                        if (JSONObj.isNow) {
                            $('today_button').removeClassName('ui-state-active');
                            $('today_button').addClassName('ui-state-disabled');
                        }
                        else {
                            $('today_button').removeClassName('ui-state-disabled');
                            $('today_button').addClassName('ui-state-active');
                        }
                        
                        processJSON(JSONObj);
                    }
                });
            }
            
            function deleteCalendarEvent(event, eventId){
                if (event) 
                    Event.stop(event);
                
                if (deleting_event) 
                    lightbox('${pageContext.request.contextPath}/account/EventDelete.action?handle', {
                        'event.id': eventId,
                        eventTitle: events.get(eventId).title
                    }, function(){
                        $$('input.ajax-nonsubmit').invoke('observe', 'click', handleAjaxNonSubmit);
                    });
            }
            
            function showMonthly(){
                $('weekView').hide();
                $('monthView').show();
                $('monthButton').addClassName('ui-state-active');
                $('weekButton').removeClassName('ui-state-active');
            }
            
            function showWeekly(){
                $('monthView').hide();
                $('weekView').show();
                $('monthButton').removeClassName('ui-state-active');
                $('weekButton').addClassName('ui-state-active');
            }
            
            function focusWeekly(){
                showWeekly();
                
                startDate = activeDay - activeDay % 7;
                endDate = activeDay + 7 - activeDay % 7;
                
                $$('div.cal-event-weekly').invoke('remove');
                
                weekdays = ['Sun ', 'Mon ', 'Tues ', 'Wed ', 'Thurs ', 'Fri ', 'Sat '];
                for (day = startDate; day < endDate; day++) {
                    monthAdjust = jsonObj.days[startDate].date > jsonObj.days[day].date || jsonObj.days[startDate].date < 10 && startDate > 30 ? jsonObj.days[day].date < 15 ? 2 : 0 : 1;
                    monthAdjust = jsonObj.month + monthAdjust > 12 ? 1 : jsonObj.month + monthAdjust;
                    $$('th.cal-col' + day % 7).invoke('update', weekdays[day % 7] + " " + monthAdjust + "/" + jsonObj.days[day].date);
                }
                if (events.each) {
                    events.each(function(pair){
                        event = pair.value;
                        if (event.startDay >= endDate || event.endDay < startDate) 
                            return;
                        if (event.startSlot != 0 || event.endSlot != 47) {
                            if (event.startDay >= startDate) {
                                weekEvent = Builder.node('div', {
                                    className: 'cal-event cal-event-skin cal-event-vert cal-corner-top cal-corner-bottom cal-event-weekly',
                                    style: 'position: absolute;'
                                }, [Builder.node('div', {
                                    className: 'cal-event-inner cal-event-skin'
                                }, [Builder.node('div', {
                                    className: 'cal-event-head cal-event-skin'
                                }, [Builder.node('div', {
                                    className: 'cal-event-time'
                                }, [event.tinyevent ? event.startTime + " " + event.title : event.startTime + " - " + event.endTime])]), (event.tinyevent ? '' : Builder.node('div', {
                                    className: 'cal-event-content'
                                }, [Builder.node('div', {
                                    className: 'cal-event-title'
                                }, [event.title])])), Builder.node('div', {
                                    className: 'cal-event-bg'
                                })])]);
                                
                                $('dayEvents').insert(weekEvent);
                                positionEvent(weekEvent, event.startCol, $('cal-slot' + event.startSlot));
                                if (event.allDays == 0 && !event.tinyevent) 
                                    weekEvent.setStyle({
                                        height: ($('cal-slot' + event.endSlot).viewportOffset()['top'] - $('cal-slot' + event.startSlot).viewportOffset()['top']) + 'px'
                                    });
                                else if (!event.tinyevent) 
                                    weekEvent.setStyle({
                                        height: ($('cal-slot' + event.startSlot).viewportOffset()['top'] - $('cal-slot' + 48).viewportOffset()['top']) + 'px'
                                    });
							}
							if (event.endDay < endDate && event.endDay != event.startDay) { 
								weekEvent = Builder.node('div', {
                                    className: 'cal-event cal-event-skin cal-event-vert cal-corner-top cal-corner-bottom cal-event-weekly',
                                    style: 'position: absolute;'
                                }, [Builder.node('div', {
                                    className: 'cal-event-inner cal-event-skin'
                                }, [Builder.node('div', {
                                    className: 'cal-event-head cal-event-skin'
                                }, [Builder.node('div', {
                                    className: 'cal-event-time'
                                }, [event.tinyevent ? event.startTime + " " + event.title : event.startTime + " - " + event.endTime])]), (event.tinyevent ? '' : Builder.node('div', {
                                    className: 'cal-event-content'
                                }, [Builder.node('div', {
                                    className: 'cal-event-title'
                                }, [event.title])])), Builder.node('div', {
                                    className: 'cal-event-bg'
                                })])]);
                                
                                $('dayEvents').insert(weekEvent);
                                positionEvent(weekEvent, event.endCol, $('cal-slot0'));
                                weekEvent.setStyle({
                                    height: ($('cal-slot' + event.endSlot).viewportOffset()['top'] - $('cal-slot0').viewportOffset()['top']) + 'px'
                                });
                            }
                            for (all = event.startDay > startDate ? event.startCol + 1 : 0; all < (event.endDay < endDate ? event.endCol : 7); all++) {
                                allDay = Builder.node('div', {
                                    className: 'cal-event cal-event-skin cal-event-hori cal-corner-left cal-corner-right cal-event-weekly',
                                    style: 'position: absolute;'
                                }, [Builder.node('div', {
                                    className: 'cal-event-innner cal-event-skin'
                                }, [Builder.node('span', {
                                    className: 'cal-event-title'
                                }, [event.title])])]);
                                
                                $('allDayEvents').insert(allDay);
                                positionEvent(allDay, all, $('allDay'));
                                allDay.setStyle({
                                    height: Math.floor(allDay.getHeight() / 2) + 'px'
                                });
                            }
                        }
                    });
                    new Effect.ScrollTo($('cal-slot18'));
                }
            }
            
            function handlePrev(){
                if ($('monthView').visible()) 
                    invoke($('hidden_form'), 'prev');
                else {
                    activeDay -= 7;
                    if (activeDay < 0) {
                        invoke($('hidden_form'), 'prev');
                        Element.observe(document, 'csd:json', focus);
                    }
                    focusWeekly();
                }
            }
            
            function handleNext(){
                if ($('monthView').visible()) 
                    invoke($('hidden_form'), 'next');
                else {
                    activeDay += 7;
                    if (activeDay > 42) {
                        invoke($('hidden_form'), 'next');
                        Element.observe(document, 'csd:json', focus);
                    }
                    else 
                        focusWeekly();
                }
            }
            
            function handleToday(){
                invoke($('hidden_form'), 'today');
                if ($('weekView').visible()) {
                    Element.observe(document, 'csd:json', focus);
                }
            }
            
            function focus(){
                focusWeekly();
                Element.stopObserving(document, 'csd:json', focus)
            }
            
            Event.observe(window, 'dom:loaded', function(){
                processJSON(jsonObj);
            });
        </script>
        <script type="text/javascript" language="Javascript" src= "${pageContext.request.contextPath}/js/eventcreation.js"></script>
        <stripes:form beanclass="durst.action.account.CalendarActionBean" id="hidden_form">
            <stripes:hidden name="month" id="hidden_month" value="${todayMonth}"/><stripes:hidden name="year" id="hidden_year" value="${todayYear}"/><stripes:hidden name="cal.id" value="${cal.id}" />
        </stripes:form>
        <div class="cal ui-widget">
            <table class="cal-header" style="width:100%">
                <tr>
                    <td class="cal-header-left">
                        <span class= "cal-button cal-button-prev ui-state-default ui-corner-left">
                            <span class="cal-button-inner">
                                <span class= "cal-button-content">
                                    <span class= "cal-icon-wrap">
                                        <span class="ui-icon ui-icon-circle-triangle-w" id="prev_button" onclick="handlePrev()"></span>
                                    </span>
                                </span>
                            </span>
                        </span>
                        <span class= "cal-button cal-button-next ui-state-default ui-corner-right">
                            <span class="cal-button-inner">
                                <span class= "cal-button-content">
                                    <span class= "cal-icon-wrap">
                                        <span class="ui-icon ui-icon-circle-triangle-e" onclick="handleNext()"></span>
                                    </span>
                                </span>
                            </span>
                        </span>
                        <span class= "cal-button cal-button-today ui-state-default ui-corner-left ui-corner-right ui-state-disabled" id="today_button">
                            <span class="cal-button-inner">
                                <span class= "cal-button-content" onclick="handleToday()">today</span>
                                <span class= "cal-button-effect"></span>
                            </span>
                        </span>
                    </td>
                    <td class="cal-header-center">
                        <h2>
                            <span class="cal-header-title ui-widget-content" style="border-width: 0px" id="headerTitle"></span>
                        </h2>
                    </td>
                    <td class="cal-header-right">
                        <span class="cal-button cal-button-month ui-state-default ui-corner-left ui-state-active" id="monthButton">
                            <span class="cal-button-inner">
                                <span class="cal-button-content" onclick="showMonthly();">month</span>
                            </span>
                        </span>
                        <span class="cal-button cal-button-agendaWeek ui-state-default ui-corner-right" id="weekButton">
                            <span class="cal-button-inner">
                                <span class="cal-button-content" onclick="focusWeekly();">week</span>
                            </span>
                        </span>
                    </td>
                </tr>
                <tr>
                    <td>
                        <span class="cal-button cal-button-month ui-state-default ui-corner-left ui-corner-right ui-state-active" id="createNew" style="padding-right: 4px" onclick="$$('div.cal-day-number').each(function (elem) { new Effect.Highlight(elem, {startcolor: '#0b3e6f', endcolor: '#303030'}); }); adding_event = true; deleting_event = false;">
                            <span class="cal-button-inner">
                                <span class="cal-button-content">Create New Event</span>
                            </span>
                        </span>
                    </td>
                    <td />
                    <td>
                        <span class="cal-button cal-button-today ui-state-default ui-corner-left ui-corner-right ui-state-active" id="deleteEvnt" style="padding-left: 33px; float: right;" onclick="$$('div.cal-event').each(function (elem) { new Effect.Highlight(elem, {startcolor: '#ffff99', endcolor: '#0b3e6f'}); }); $$('div.cal-event-inner').each(function (elem) { new Effect.Highlight(elem, {startcolor: '#ffff99', endcolor: '#0b3e6f'}); }); deleting_event = true; adding_event = false;">
                            <span class="cal-button-inner">
                                <span class="cal-button-content" >Delete Event</span>
                            </span>
                        </span>
                    </td>
                </tr>
            </table>
            <div class="cal-content" style="position: relative; min-height: 1px; ">
                <div class="cal-view cal-view-month cal-grid" style="position: relative; display: block; " unselectable="on" id="monthView">
                    <table class="cal-border-separate" style="width:100%" cellspacing="0">
                        <thead>
                            <tr class="cal-first cal-last">
                                <c:forEach var="day" items="${fn:split('Sun|Mon|Tue|Wed|Thu|Fri|Sat','|')}">
                                    <th class="cal-mon ui-widget-header ${day == 'Sun' ? 'cal-first' : (day == 'Sat' ? 'cal-last' : '')}" style="width: 127px; ">${day}</th>
                                </c:forEach>
                            </tr>
                        </thead>
                        <tbody id="monthlyBody">
                            <c:set var="dayCount" scope="page" value="0" />
                            <c:forEach var="week" begin="0" end="5">
                                <tr class="cal-week${week} ${week == 0 ? 'cal-first' : (week == 5 ? 'cal-last' : '')}">
                                    <c:forEach var="day" items="${fn:split('sun|mon|tue|wed|thu|fri|sat','|')}">
                                        <td class="cal-${day} ui-widget-content cal-day${dayCount} ${day == 'sun' ? 'cal-first' : (day == 'sat' ? 'cal-last' : '')}" style="width:127px;" onclick="addCalendarEvent(null, parseInt('${dayCount}'), '${pageContext.request.contextPath}/account/EventCreate.action', null, cal_id, adding_event, startTime); adding_event = false;">
                                            <c:if test="${day == 'sun'}">
                                            <div style="min-height: 107px"></c:if>
                                            <div class="cal-day-number" id="cal-day${dayCount}">0</div>
                                            <div class="cal-day-content" id="cal-day${dayCount}-content">
                                                <div style="position: relative;">&nbsp;</div>
                                            </div>
                                            <c:set var="dayCount" scope="page" value="${dayCount + 1}" />
                                            <c:if test="${day == 'sun'}"></div>
                                        </c:if>
                                    </td>
                                    </c:forEach>
                                </tr>
                            </c:forEach>
                        </tbody>
                    </table>
                </div>
                <div class="cal-view cal-view-agendaWeek cal-agenda" style="position: relative; display: none; " unselectable="on" id="weekView">
                    <table style="width:100%" class="cal-agenda-days cal-border-separate" cellspacing="0">
                        <thead>
                            <tr class="cal-first cal-last">
                                <th class="cal-agenda-axis ui-widget-header cal-first" style="width: 50px; ">&nbsp;</th>
                                <c:forEach items="${fn:split('Sun|Mon|Tue|Wed|Thu|Fri|Sat','|')}" var="day" varStatus="ndx">
                                    <th class="cal-${fn:toLowerCase(day)} cal-col${ndx.index} ui-widget-header" style="width: 117px; ">
                                        ${day} 
                                        <span/>
                                    </th>
                                </c:forEach>
                                <th class="cal-agenda-gutter ui-widget-header cal-last" style="width: 13px; ">&nbsp;</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr class="cal-first cal-last">
                                <th class="cal-agenda-axis ui-widget-header cal-first">&nbsp;</th>
                                <c:forEach items="${fn:split('sun|mon|tue|wed|thu|fri|sat','|')}" var="day" varStatus="ndx">
                                    <td class="cal-${day} cal-col${ndx.index} ui-widget-content" id="cal-col${ndx.index}" onclick="addCalendarEvent(null, activeDay + ${ndx.index}, '${pageContext.request.contextPath}/account/EventCreate.action', null, cal_id, adding_event, startTime); adding_event = false;">
                                        <div style="height: 648px; ">
                                            <div class="cal-day-content">
                                                <div style="position:relative">&nbsp;</div>
                                            </div>
                                        </div>
                                    </td>
                                </c:forEach>
                                <td class="cal-agenda-gutter ui-widget-content cal-last" style="width: 13px; ">&nbsp;</td>
                            </tr>
                        </tbody>
                    </table>
                    <div style="position: absolute; z-index: 2; left: 0px; width: 100%; top: 18px; ">
                        <div style="position:absolute;z-index:8;top:0;left:0" id="allDayEvents"></div>
                        <table style="width:100%" class="cal-agenda-allday" cellspacing="0" id="allDay">
                            <tbody>
                                <tr>
                                    <th class="ui-widget-header cal-agenda-axis" style="width: 50px; ">all-day</th>
                                    <td>
                                        <div class="cal-day-content">
                                            <div style="position: relative; height: 0px; "></div>
                                        </div>
                                    </td>
                                    <th class="ui-widget-header cal-agenda-gutter" style="width: 13px; ">&nbsp;</th>
                                </tr>
                            </tbody>
                        </table>
                        <div class="cal-agenda-divider ui-widget-header">
                            <div class="cal-agenda-divider-inner"></div>
                        </div>
                        <div style="position: absolute; width: 100%; overflow-x: hidden; overflow-y: auto; height: 607px; ">
                            <div style="position:relative;width:100%;overflow:hidden">
                                <div style="position: absolute; z-index: 8; top: 0; left: 0;" id="dayEvents"></div>
                                <table class="cal-agenda-slots" style="width:100%" cellspacing="0">
                                    <tbody>
                                        <c:forEach items="${fn:split('12am|1am|2am|3am|4am|5am|6am|7am|8am|9am|10am|11am|12pm|1pm|2pm|3pm|4pm|5pm|6pm|7pm|8pm|9pm|10pm|11pm','|')}" varStatus="ndx" var="day">
                                            <tr class="cal-slot${ndx.index*2} " id="cal-slot${ndx.index*2}">
                                                <th class="cal-agenda-axis ui-widget-header" style="width: 50px; ">${day}</th>
                                                <td class="ui-widget-content">
                                                    <div style="position:relative">&nbsp;</div>
                                                </td>
                                            </tr>
                                            <tr class="cal-slot${ndx.index*2 + 1} cal-minor" id="cal-slot${ndx.index*2 + 1}">
                                                <th class="cal-agenda-axis ui-widget-header">&nbsp;</th>
                                                <td class="ui-widget-content">
                                                    <div style="position:relative">&nbsp;</div>
                                                </td>
                                            </tr>
                                        </c:forEach>
                                        <tr id="cal-slot48" style="display: none;">
                                        <th class="cal-agenda-axis ui-widget-header">&nbsp;</th>
                                        <td class="ui-widget-content">
                                            <div style="position:relative">&nbsp;</div>
                                        </td>
                                        </th>
                                    </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </stripes:layout-component>
</stripes:layout-render>
